import React, { useState, useEffect, useRef } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { Form, Input, Button, Alert, Typography } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { useAuthStore } from '../../stores/authStore';
import GlitchBackgroundWrapper from '../../components/layout/GlitchBackgroundWrapper';
import { motion } from 'framer-motion';

const { Title, Text } = Typography;

interface LoginFormData {
  email: string;
  password: string;
}

const LoginPage: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const { login, isLoading, error, isAuthenticated, clearError } = useAuthStore();
  const [form] = Form.useForm();
  const redirecting = useRef(false);

  // 如果已经登录且不在加载状态，重定向到dashboard
  useEffect(() => {
    if (!redirecting.current && isAuthenticated && !isLoading) {
      console.log('用户已认证，重定向到dashboard');
      redirecting.current = true;
      // 检查是否有重定向地址
      const from = location.state?.from?.pathname || '/dashboard';
      navigate(from, { replace: true });
    }
  }, [isAuthenticated, isLoading, navigate, location.state]);

  // 清除错误信息
  useEffect(() => {
    return () => {
      clearError();
    };
  }, [clearError]);

  const handleSubmit = async (values: LoginFormData) => {
    const success = await login(values.email, values.password);
    if (success && !redirecting.current) {
      console.log('登录成功，重定向到dashboard');
      redirecting.current = true;
      // 检查是否有重定向地址
      const from = location.state?.from?.pathname || '/dashboard';
      navigate(from, { replace: true });
    }
  };

  return (
    <GlitchBackgroundWrapper>
      {/* 导航栏 */}
      <motion.nav 
        style={{
          position: 'absolute',
          top: 0,
          left: 0,
          right: 0,
          zIndex: 3,
          padding: '1rem 2rem',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          backgroundColor: 'rgba(0, 0, 0, 0.2)',
          backdropFilter: 'blur(10px)',
          borderBottom: '1px solid rgba(255, 255, 255, 0.1)'
        }}
        initial={{ y: -50, opacity: 0 }}
        animate={{ y: 0, opacity: 1 }}
        transition={{ duration: 0.5 }}
      >
        <motion.div
          style={{
            display: 'flex',
            alignItems: 'center',
            color: 'white',
            fontWeight: 'bold',
            fontSize: '1.2rem',
            cursor: 'pointer'
          }}
          onClick={() => navigate('/')}
          whileHover={{ scale: 1.05 }}
          whileTap={{ scale: 0.95 }}
        >
          <motion.span 
            style={{ marginRight: '0.5rem' }}
            animate={{ 
              rotate: [0, 10, -10, 0],
              transition: { 
                duration: 2,
                repeat: Infinity,
                repeatType: "reverse"
              }
            }}
          >
            ⚡
          </motion.span>
          FastAPI Platform
        </motion.div>
        <div style={{
          display: 'flex',
          gap: '2rem'
        }}>
          <motion.button
            onClick={() => navigate('/')}
            style={{
              color: 'white',
              background: 'none',
              border: 'none',
              fontSize: '1rem',
              fontWeight: '500',
              cursor: 'pointer',
              transition: 'all 0.3s ease'
            }}
            whileHover={{ scale: 1.1 }}
            whileTap={{ scale: 0.9 }}
          >
            返回首页
          </motion.button>
        </div>
      </motion.nav>

      {/* 登录表单区域 */}
      <div style={{
        position: 'relative',
        zIndex: 2,
        width: '100%',
        height: '100%',
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
        padding: '20px'
      }}>
        {/* 登录框 */}
        <motion.div 
          style={{
            width: '100%',
            maxWidth: '400px',
            padding: '2.5rem',
            backgroundColor: 'rgba(0, 0, 0, 0.4)',
            backdropFilter: 'blur(15px)',
            border: '1px solid rgba(255, 255, 255, 0.1)',
            borderRadius: '20px',
            boxShadow: '0 8px 32px rgba(0, 0, 0, 0.3)',
            position: 'relative',
            overflow: 'hidden'
          }}
          initial={{ opacity: 0, y: 50 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5 }}
        >
          {/* 顶部装饰线 */}
          <div style={{
            position: 'absolute',
            top: 0,
            left: 0,
            right: 0,
            height: '2px',
            background: 'linear-gradient(90deg, transparent, #61dca3, transparent)',
            animation: 'shimmer 2s infinite'
          }} />

          {/* 标题 */}
          <motion.div 
            style={{
              textAlign: 'center',
              marginBottom: '2rem'
            }}
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ duration: 0.5, delay: 0.2 }}
          >
            <Title level={2} style={{
              fontSize: '2rem',
              fontWeight: 'bold',
              marginBottom: '0.5rem',
              background: 'linear-gradient(90deg, #ffffff, #61dca3)',
              WebkitBackgroundClip: 'text',
              WebkitTextFillColor: 'transparent',
              animation: 'textGlow 3s ease-in-out infinite alternate'
            }}>
              登录
            </Title>
            <Text style={{
              color: 'rgba(255, 255, 255, 0.7)',
              fontSize: '0.95rem'
            }}>
              登录到您的账户
            </Text>
          </motion.div>

          {/* 错误提示 */}
          {error && (
            <motion.div
              initial={{ opacity: 0, y: -10 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.3 }}
            >
              <Alert
                message={error}
                type="error"
                showIcon
                style={{ marginBottom: '1rem' }}
                onClose={clearError}
                closable
              />
            </motion.div>
          )}

          {/* 表单 */}
          <Form
            form={form}
            name="login"
            onFinish={handleSubmit}
            size="large"
            style={{ width: '100%' }}
          >
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.3, delay: 0.3 }}
            >
              <Form.Item
                name="email"
                rules={[
                  { required: true, message: '请输入邮箱地址' },
                  { type: 'email', message: '请输入有效的邮箱地址' }
                ]}
              >
                <Input
                  prefix={<UserOutlined style={{ color: 'rgba(255, 255, 255, 0.6)' }} />}
                  placeholder="邮箱地址"
                  autoComplete="email"
                  style={{
                    backgroundColor: 'rgba(255, 255, 255, 0.05)',
                    border: '1px solid rgba(255, 255, 255, 0.2)',
                    borderRadius: '10px',
                    color: 'white',
                    padding: '12px 16px'
                  }}
                />
              </Form.Item>
            </motion.div>

            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.3, delay: 0.4 }}
            >
              <Form.Item
                name="password"
                rules={[
                  { required: true, message: '请输入密码' },
                  { min: 6, message: '密码长度至少6位' }
                ]}
              >
                <Input.Password
                  prefix={<LockOutlined style={{ color: 'rgba(255, 255, 255, 0.6)' }} />}
                  placeholder="密码"
                  autoComplete="current-password"
                  style={{
                    backgroundColor: 'rgba(255, 255, 255, 0.05)',
                    border: '1px solid rgba(255, 255, 255, 0.2)',
                    borderRadius: '10px',
                    color: 'white',
                    padding: '12px 16px'
                  }}
                />
              </Form.Item>
            </motion.div>

            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.3, delay: 0.5 }}
            >
              <Form.Item>
                <motion.div
                  whileHover={{ scale: 1.02 }}
                  whileTap={{ scale: 0.98 }}
                >
                  <Button
                    type="primary"
                    htmlType="submit"
                    loading={isLoading}
                    style={{
                      width: '100%',
                      height: '50px',
                      fontSize: '1.1rem',
                      fontWeight: 'bold',
                      backgroundColor: '#61dca3',
                      borderColor: '#61dca3',
                      borderRadius: '12px'
                    }}
                  >
                    {isLoading ? '登录中...' : '登录'}
                  </Button>
                </motion.div>
              </Form.Item>
            </motion.div>
          </Form>

          {/* 底部链接 */}
          <motion.div 
            style={{
              marginTop: '1.5rem',
              textAlign: 'center',
              paddingTop: '1.5rem',
              borderTop: '1px solid rgba(255, 255, 255, 0.1)'
            }}
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ duration: 0.5, delay: 0.6 }}
          >
            <Text style={{
              color: 'rgba(255, 255, 255, 0.7)',
              fontSize: '0.9rem'
            }}>
              还没有账户？{' '}
              <motion.span
                whileHover={{ scale: 1.05 }}
                whileTap={{ scale: 0.95 }}
              >
                <Button
                  type="link"
                  style={{
                    color: '#61dca3',
                    fontSize: '0.9rem',
                    fontWeight: '500',
                    padding: 0
                  }}
                  onClick={() => navigate('/signup')}
                >
                  立即注册
                </Button>
              </motion.span>
            </Text>
          </motion.div>
        </motion.div>
      </div>

      {/* CSS 动画样式 */}
      <style>
        {`
          @keyframes fadeInUp {
            from {
              opacity: 0;
              transform: translateY(30px);
            }
            to {
              opacity: 1;
              transform: translateY(0);
            }
          }

          @keyframes shimmer {
            0% {
              transform: translateX(-100%);
            }
            100% {
              transform: translateX(100%);
            }
          }

          @keyframes textGlow {
            0% {
              text-shadow: 0 0 10px rgba(97, 220, 163, 0.3);
            }
            100% {
              text-shadow: 0 0 20px rgba(97, 220, 163, 0.6), 0 0 30px rgba(97, 220, 163, 0.4);
            }
          }

          /* Ant Design 自定义样式 */
          .ant-input::placeholder {
            color: rgba(255, 255, 255, 0.5) !important;
          }
          
          .ant-input:focus {
            border-color: #61dca3 !important;
            box-shadow: 0 0 0 2px rgba(97, 220, 163, 0.2) !important;
          }
          
          .ant-input-password .ant-input:focus {
            border-color: #61dca3 !important;
            box-shadow: none !important;
          }
          
          .ant-btn:hover {
            background-color: #4fc085 !important;
            border-color: #4fc085 !important;
            transform: translateY(-1px);
            box-shadow: 0 6px 20px rgba(97, 220, 163, 0.4);
          }
        `}
      </style>
    </GlitchBackgroundWrapper>
  );
};

export default LoginPage;